<template>
  <div class="tag-container" ref="outerElment">
    <div class="scroll gap-row-8" ref="scrollElement">
      <Tag
        v-for="item in props.items"
        :key="`search-result-tag-${item[`${props.itemValue}`]}`"
        :value="item[`${props.itemValue}`]"
        :label="item[`${itemLabel}`]"
        :selected-bg="modelValue === item[`${props.itemValue}`] && theme === 'light'"
        :dark="theme === 'dark'"
        :selected="modelValue === item[`${props.itemValue}`] && theme === 'dark'"
        :active="modelValue === item[`${props.itemValue}`] && theme === 'gradient'"
        :disabled="item[`${props.itemActive}`] === false"
        @click="onTagClick(item)"
        ref="itemRefs"
      ></Tag>
    </div>
    <SwipeArrow
      :show-on-mobile="showOnMobile"
      :show-left="showLeft"
      :show-right="showRight"
      :to-left="moveToLeft"
      :to-right="moveToRight"
    >
    </SwipeArrow>
  </div>
</template>
<script setup>
import { computed, onActivated, onMounted, ref } from 'vue'
import { useHorizontalScroll } from '@/compositions/sensor/horizontal-scroll'
import SwipeArrow from './SwipeArrow.vue'
import Tag from './Tag.vue'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: '',
  },
  items: { type: Array, required: true },
  itemValue: { type: String, default: 'value' },
  itemLabel: { type: String, default: 'label' },
  itemActive: { type: String, default: 'active' },
  theme: { type: String, default: 'light' },
  checker: { type: Function, required: false },
  showOnMobile: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'click'])

const modelValue = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

const outerElment = ref(null)
const scrollElement = ref(null)
const itemRefs = ref([])
const activeIndex = computed(() => props.items.findIndex((item) => item[`${props.itemValue}`] === modelValue.value))

const { showLeft, showRight, normalizeToLeft, moveToItem, moveToLeft, moveToRight } = useHorizontalScroll(
  outerElment,
  scrollElement,
  itemRefs,
)

onMounted(() => {
  normalizeToLeft()
  setTimeout(() => moveToItem(activeIndex.value), 500)
})
onActivated(() => {
  normalizeToLeft()
  setTimeout(() => moveToItem(activeIndex.value), 500)
})

function onTagClick(item) {
  emit('click', item)
  if (props.checker && !props.checker(item)) return
  modelValue.value = item[`${props.itemValue}`]
}
</script>
<style scoped lang="scss">
.tag-container {
  position: relative;
  width: 100%;

  .scroll {
    display: flex;
    width: 100%;
    max-width: 100%;
    overflow-x: auto;
  }
}
</style>
